#!/bin/bash
#
# This Script made by haven200
# 21:55 22/01/2016
#
### BEGIN INIT INFO
# Provides:          sdcard
# Required-Start:    $all
# Required-Stop:     $all
# Should-Start:
# Should-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

name="sdcard"
sdcard_pid="/var/run/$name.pid"
sdcard_device="/dev/mmcblk0p1"
sdcard_dir="/media/sdcard"

. /lib/lsb/init-functions

make_dir() {
    if [ ! -d "$1" ]; then
        mkdir -p "$1"
    fi
}

do_mount() {
    make_dir "$sdcard_dir"
    mount "$sdcard_device" "$sdcard_dir"
    sleep 1
}

do_umount() {
    umount "$sdcard_device"
}

do_start() {
    num=6
    while [ $num -gt 0 ]
    do
        echo "num=$num"
        sleep 60 
        umount "$sdcard_device"
        if [ "X$?" = "X0" ]; then 
            echo "sdcard....Error=$?,break"
            break
        fi 
        num=$(($num-1)) 
    done
}

do_stop() {
    do_umount
}

do_update() {
    do_umount
    sleep 2
    do_mount
    sleep 2
    cp -Ru /boot/* "$sdcard_dir"
    sleep 6
    do_umount
}

save_pid() {
    echo "$$" > "$sdcard_pid"
}
remove_pid(){
    if [ -f "$sdcard_pid" ]; then 
        rm "$sdcard_pid"
    fi
}

save_pid

case "$1" in
  start)
    log_daemon_msg "Unmounting folder...." "$name"
    do_start "$sdcard"
    log_end_msg $?
    ;;
  update)
    log_daemon_msg "Mounting sd card...." "$name"
    do_update
    log_end_msg $?
    ;;
  stop)
    #log_daemon_msg "Unmounting folder...." "$name"
    #do_stop
    #log_end_msg $?
    ;;
  *)
    log_action_msg "Usage: service $name {start|update}"
    remove_pid    
    exit 2
    ;;
esac

remove_pid
exit 0
